import re
from django.contrib.auth.backends import ModelBackend
from users.models import User


# 返回token时,增加username, user.id
def jwt_response_payload_handler(token, user=None, request=None):
    """重写jwt的登录响应函数"""
    data = {
        "username": user.username,
        "user_id": user.id,
        "token": token
    }
    return data


def get_user_by_account(account):
    try:
        if re.match(r"^1[3-9][0-9]{9}$", account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """重写校验用户名密码"""
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        if user is not None and user.check_password(password):
            return user
